<?php

namespace App\Http\Controllers\Home;

use Illuminate\Http\Request;
use App\Customers;
use App\Cat;
use Hash;
use Gregwar\Captcha\CaptchaBuilder;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class LogController extends Controller
{
    //展示登陆页
    public function getLog(){
        $cat = new Cat;
        $cats = $cat->getTree();
        return view('home.login',['cats'=>$cats]);
    }

    //登陆验证及设置session
    public function postLog(Request $request){

        $this->validate($request,[
            'name'=>'required|min:2|max:20',
            'password'=>'required|min:6|max:20'
        ],[
            'name.required' => '必须填写用户名',
            'password.required' => '必须填写密码',
            'name.min' => '用户名必须大于二',
            'password.min' => '密码必须大于六位',
            'name.max' => '用户名不能大于20',
            'password.max' => '密码不能大于20'
        ]);

        if($cus = Customers::where('name','=',$request->name)->first()){
            $builder = new CaptchaBuilder;
            if($request->session()->get('phrase') == $request->captcha) {
                if (Hash::check($request->password, $cus->password)) {
                    $rem = md5($cus->email . $cus->name);
                    $request->session()->put('remt', $rem);
                    $request->session()->put('name', $cus->name);

                    $request->session()->put('uid', $cus->uid);
                    if($adds = $request->session()->get('address')){
                        $parm = $request->session()->get('parm');
                        $adds = "Home" . '\\' . $adds;
                        return redirect()->action($adds, $parm);
                    }else{
                        return redirect('/');
                    }

                }
            }
        }
        return back();
        
    }

    //退出登录
    public function logout(Request $request){
        $request->session()->forget('remt');
        return redirect('/');
    }

    //验证码专用方法
    public function capt(Request $req){
        $builder = new CaptchaBuilder;
        $builder->build();
        header('Content-type:image/jpeg');
        $builder->output();
        $req->session()->put('phrase',$builder->getPhrase());
    }
}
